<template>
  <div class="ai-generator">
    <!-- AI代码生成器 -->
    <el-card class="ai-config-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Magic /></el-icon>
          <span>AI智能代码生成</span>
          <el-tag type="success" size="small" style="margin-left: 8px;">Beta</el-tag>
        </div>
      </template>

      <!-- 步骤指示 -->
      <el-steps :active="currentStep" align-center class="steps">
        <el-step title="数据库分析" icon="DataBoard" />
        <el-step title="业务推理" icon="BrainFilled" />
        <el-step title="代码生成" icon="Magic" />
        <el-step title="代码预览" icon="View" />
      </el-steps>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 步骤1: 数据库分析 -->
        <div v-show="currentStep === 0" class="analysis-step">
          <h3>📊 数据库结构分析</h3>
          
          <div class="analysis-options">
            <el-radio-group v-model="analysisSource" @change="onAnalysisSourceChange">
              <el-radio value="imported">使用已导入的表结构</el-radio>
              <el-radio value="sql">上传SQL文件</el-radio>
              <el-radio value="manual">手动输入表结构</el-radio>
            </el-radio-group>
          </div>

          <!-- SQL文件上传 -->
          <div v-if="analysisSource === 'sql'" class="sql-upload">
            <el-upload
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleSQLFileChange"
              accept=".sql"
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将SQL文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持MySQL、PostgreSQL、SQLite的DDL语句
                </div>
              </template>
            </el-upload>
          </div>

          <!-- 手动输入 -->
          <div v-if="analysisSource === 'manual'" class="manual-input">
            <el-input
              v-model="manualSQL"
              type="textarea"
              :rows="10"
              placeholder="请输入CREATE TABLE语句..."
            />
          </div>

          <!-- 分析结果 -->
          <div v-if="analysisResult" class="analysis-result">
            <h4>🔍 分析结果</h4>
            <div class="result-summary">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="数据表数量">
                  {{ analysisResult.tables.length }}
                </el-descriptions-item>
                <el-descriptions-item label="业务领域">
                  {{ analysisResult.businessDomains.length }}
                </el-descriptions-item>
                <el-descriptions-item label="表关系">
                  {{ analysisResult.relationships.length }}
                </el-descriptions-item>
                <el-descriptions-item label="推荐API">
                  {{ analysisResult.suggestedAPIs.length }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <div class="tables-preview">
              <h5>📋 数据表预览</h5>
              <el-table :data="analysisResult.tables" style="width: 100%">
                <el-table-column prop="name" label="表名" width="200" />
                <el-table-column prop="purpose" label="业务用途" />
                <el-table-column prop="businessType" label="表类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getTableTypeColor(row.businessType)" size="small">
                      {{ getTableTypeLabel(row.businessType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="字段数" width="80">
                  <template #default="{ row }">
                    {{ row.fields.length }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>

        <!-- 步骤2: 业务推理 -->
        <div v-show="currentStep === 1" class="business-step">
          <h3>🧠 业务逻辑推理</h3>
          
          <div class="business-domains">
            <h4>业务领域划分</h4>
            <div class="domain-cards">
              <div 
                v-for="domain in businessDomains" 
                :key="domain.name"
                class="domain-card"
                :class="{ active: selectedDomain?.name === domain.name }"
                @click="selectDomain(domain)"
              >
                <h5>{{ domain.name }}</h5>
                <p>{{ domain.description }}</p>
                <div class="domain-tables">
                  <el-tag 
                    v-for="table in domain.tables" 
                    :key="table"
                    size="small"
                    style="margin: 2px;"
                  >
                    {{ table }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <div v-if="selectedDomain" class="business-config">
            <h4>业务配置 - {{ selectedDomain.name }}</h4>
            
            <el-form :model="businessConfig" label-width="120px">
              <el-form-item label="生成模块">
                <el-checkbox-group v-model="businessConfig.modules">
                  <el-checkbox 
                    v-for="module in selectedDomain.suggestedModules"
                    :key="module"
                    :value="module"
                  >
                    {{ module }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="API风格">
                <el-radio-group v-model="businessConfig.apiStyle">
                  <el-radio value="restful">RESTful API</el-radio>
                  <el-radio value="graphql">GraphQL</el-radio>
                  <el-radio value="rpc">RPC风格</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="业务特性">
                <el-checkbox-group v-model="businessConfig.features">
                  <el-checkbox value="validation">数据验证</el-checkbox>
                  <el-checkbox value="pagination">分页查询</el-checkbox>
                  <el-checkbox value="search">搜索功能</el-checkbox>
                  <el-checkbox value="export">数据导出</el-checkbox>
                  <el-checkbox value="audit">操作审计</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="自定义需求">
                <el-input
                  v-model="businessConfig.customRequirements"
                  type="textarea"
                  :rows="3"
                  placeholder="描述特殊的业务需求..."
                />
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 步骤3: 代码生成 -->
        <div v-show="currentStep === 2" class="generation-step">
          <h3>⚡ AI代码生成</h3>
          
          <div class="generation-config">
            <el-form :model="generationConfig" label-width="120px">
              <el-form-item label="AI模型">
                <el-select v-model="generationConfig.aiModel" style="width: 100%">
                  <el-option label="GPT-4" value="gpt-4" />
                  <el-option label="Claude-3" value="claude-3" />
                  <el-option label="本地模型" value="local" />
                </el-select>
              </el-form-item>

              <el-form-item label="代码风格">
                <el-select v-model="generationConfig.codeStyle" style="width: 100%">
                  <el-option label="标准风格" value="standard" />
                  <el-option label="简洁风格" value="minimal" />
                  <el-option label="详细注释" value="verbose" />
                </el-select>
              </el-form-item>

              <el-form-item label="生成内容">
                <el-checkbox-group v-model="generationConfig.components">
                  <el-checkbox value="entity">实体类</el-checkbox>
                  <el-checkbox value="repository">数据访问层</el-checkbox>
                  <el-checkbox value="service">业务逻辑层</el-checkbox>
                  <el-checkbox value="controller">控制器</el-checkbox>
                  <el-checkbox value="dto">数据传输对象</el-checkbox>
                  <el-checkbox value="test">单元测试</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>

          <div class="prompt-preview">
            <h4>🤖 AI提示词预览</h4>
            <el-input
              v-model="generatedPrompt"
              type="textarea"
              :rows="8"
              readonly
              class="prompt-text"
            />
          </div>

          <div class="generation-actions">
            <el-button 
              type="primary" 
              size="large"
              @click="generateCode"
              :loading="generating"
            >
              <el-icon><Magic /></el-icon>
              开始生成代码
            </el-button>
          </div>
        </div>

        <!-- 步骤4: 代码预览 -->
        <div v-show="currentStep === 3" class="preview-step">
          <h3>👀 生成代码预览</h3>
          
          <div v-if="generatedCode.length > 0" class="code-preview">
            <el-tabs v-model="activeCodeTab" type="card">
              <el-tab-pane 
                v-for="code in generatedCode"
                :key="code.filename"
                :label="code.filename"
                :name="code.filename"
              >
                <div class="code-header">
                  <span class="code-type">{{ getCodeTypeLabel(code.type) }}</span>
                  <span class="code-description">{{ code.description }}</span>
                  <div class="code-actions">
                    <el-button size="small" @click="copyCode(code.content)">
                      <el-icon><CopyDocument /></el-icon>
                      复制
                    </el-button>
                    <el-button size="small" @click="downloadCode(code)">
                      <el-icon><Download /></el-icon>
                      下载
                    </el-button>
                  </div>
                </div>
                <pre class="code-content"><code>{{ code.content }}</code></pre>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div class="preview-actions">
            <el-button type="success" size="large" @click="downloadAllCode">
              <el-icon><Download /></el-icon>
              下载全部代码
            </el-button>
            <el-button @click="regenerateCode">
              <el-icon><Refresh /></el-icon>
              重新生成
            </el-button>
          </div>
        </div>
      </div>

      <!-- 底部操作 -->
      <div class="step-actions">
        <el-button @click="prevStep" :disabled="currentStep === 0">
          <el-icon><ArrowLeft /></el-icon>
          上一步
        </el-button>
        <el-button 
          v-if="currentStep < 3" 
          type="primary" 
          @click="nextStep"
          :disabled="!canProceed"
        >
          下一步
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Magic, DataBoard, BrainFilled, View, UploadFilled, 
  ArrowLeft, ArrowRight, CopyDocument, Download, Refresh
} from '@element-plus/icons-vue'
import { aiCodeGeneratorService, type BusinessDomain, type GeneratedCode } from '../services/aiCodeGenerator'

// 响应式数据
const currentStep = ref(0)
const analysisSource = ref('imported')
const manualSQL = ref('')
const analysisResult = ref<any>(null)
const businessDomains = ref<BusinessDomain[]>([])
const selectedDomain = ref<BusinessDomain | null>(null)
const generatedPrompt = ref('')
const generatedCode = ref<GeneratedCode[]>([])
const activeCodeTab = ref('')
const generating = ref(false)

// 业务配置
const businessConfig = reactive({
  modules: [] as string[],
  apiStyle: 'restful',
  features: [] as string[],
  customRequirements: ''
})

// 生成配置
const generationConfig = reactive({
  aiModel: 'gpt-4',
  codeStyle: 'standard',
  components: ['entity', 'repository', 'service', 'controller'] as string[]
})

// 计算属性
const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0: return analysisResult.value !== null
    case 1: return selectedDomain.value !== null
    case 2: return generatedPrompt.value.length > 0
    default: return true
  }
})

// 方法
const onAnalysisSourceChange = () => {
  analysisResult.value = null
}

const handleSQLFileChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const sql = e.target?.result as string
    analyzeSQLContent(sql)
  }
  reader.readAsText(file.raw)
}

const analyzeSQLContent = async (sql: string) => {
  try {
    // 这里调用SQL分析服务
    // 模拟分析结果
    analysisResult.value = {
      tables: [
        {
          name: 'users',
          purpose: '用户管理',
          businessType: 'master',
          fields: [
            { name: 'id', type: 'bigint', primaryKey: true },
            { name: 'username', type: 'varchar', nullable: false },
            { name: 'email', type: 'varchar', nullable: false }
          ]
        }
      ],
      relationships: [],
      businessDomains: [
        {
          name: '用户管理',
          tables: ['users'],
          description: '用户相关的业务逻辑',
          suggestedModules: ['UserModule']
        }
      ],
      suggestedAPIs: [
        'GET /users - 查询用户列表',
        'POST /users - 创建用户'
      ]
    }
    
    businessDomains.value = analysisResult.value.businessDomains
    ElMessage.success('数据库分析完成')
  } catch (error) {
    ElMessage.error('分析失败，请检查SQL格式')
  }
}

const selectDomain = (domain: BusinessDomain) => {
  selectedDomain.value = domain
  businessConfig.modules = [...domain.suggestedModules]
}

const generateCode = async () => {
  if (!selectedDomain.value) return
  
  generating.value = true
  try {
    // 生成提示词
    const prompt = aiCodeGeneratorService.generatePrompt({
      framework: 'Spring Boot',
      language: 'Java',
      database: 'MySQL',
      businessDomain: selectedDomain.value,
      tableSchema: analysisResult.value.tables[0],
      relatedTables: [],
      requirements: [
        businessConfig.customRequirements,
        ...businessConfig.features.map(f => `支持${f}`)
      ].filter(Boolean)
    })
    
    generatedPrompt.value = prompt
    
    // 调用AI生成代码
    const codes = await aiCodeGeneratorService.generateCode(prompt)
    generatedCode.value = codes
    
    if (codes.length > 0) {
      activeCodeTab.value = codes[0].filename
    }
    
    ElMessage.success('代码生成完成')
    nextStep()
  } catch (error) {
    ElMessage.error('代码生成失败')
  } finally {
    generating.value = false
  }
}

const copyCode = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('代码已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}

const downloadCode = (code: GeneratedCode) => {
  const blob = new Blob([code.content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = code.filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const downloadAllCode = () => {
  // 创建ZIP文件下载所有代码
  ElMessage.info('打包下载功能开发中...')
}

const regenerateCode = () => {
  currentStep.value = 2
  generatedCode.value = []
}

const nextStep = () => {
  if (currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 辅助方法
const getTableTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    master: 'primary',
    transaction: 'success',
    lookup: 'info',
    log: 'warning'
  }
  return colors[type] || 'default'
}

const getTableTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    master: '主数据',
    transaction: '事务表',
    lookup: '字典表',
    log: '日志表'
  }
  return labels[type] || type
}

const getCodeTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    controller: '控制器',
    service: '服务层',
    model: '实体类',
    dto: '数据传输对象',
    repository: '数据访问层'
  }
  return labels[type] || type
}

// 初始化
onMounted(() => {
  // 如果有已导入的表结构，自动分析
  if (analysisSource.value === 'imported') {
    // 获取已导入的表结构
    // mockAnalysis()
  }
})
</script>

<style scoped lang="scss">
.ai-generator {
  padding: 24px;
}

.ai-config-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 16px;
    
    .header-icon {
      color: #722ed1;
    }
  }
}

.steps {
  margin: 32px 0;
}

.step-content {
  min-height: 400px;
  padding: 24px 0;
  
  h3 {
    font-size: 20px;
    margin-bottom: 24px;
    color: #303133;
  }
  
  h4 {
    font-size: 16px;
    margin: 20px 0 12px;
    color: #606266;
  }
  
  h5 {
    font-size: 14px;
    margin: 16px 0 8px;
    color: #909399;
  }
}

.analysis-options {
  margin-bottom: 24px;
}

.sql-upload {
  margin: 24px 0;
}

.analysis-result {
  margin-top: 24px;
  
  .result-summary {
    margin-bottom: 20px;
  }
}

.domain-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.domain-card {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #722ed1;
    box-shadow: 0 2px 8px rgba(114, 46, 209, 0.15);
  }
  
  &.active {
    border-color: #722ed1;
    background: #f9f0ff;
  }
  
  h5 {
    margin: 0 0 8px;
    color: #303133;
  }
  
  p {
    margin: 0 0 12px;
    color: #606266;
    font-size: 13px;
  }
}

.business-config {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.generation-config {
  margin-bottom: 24px;
}

.prompt-preview {
  margin: 24px 0;
  
  .prompt-text {
    font-family: 'Courier New', monospace;
    font-size: 12px;
  }
}

.generation-actions {
  text-align: center;
  margin: 24px 0;
}

.code-preview {
  margin-bottom: 24px;
}

.code-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 12px;
  
  .code-type {
    background: #722ed1;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }
  
  .code-description {
    color: #606266;
    font-size: 13px;
  }
  
  .code-actions {
    margin-left: auto;
  }
}

.code-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  max-height: 400px;
  overflow-y: auto;
}

.preview-actions {
  text-align: center;
  margin: 24px 0;
}

.step-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
  margin-top: 24px;
}
</style>



